const connection = require('../../sql');

class PrintService {
	async createPrint({ title, create_id, updata_id }) {
		const conn = await connection.getConnection();
		try {
			await conn.beginTransaction();
			const now = new Date();
			const sql = `
        INSERT INTO sys_print (title, create_id, updata_id, create_at, updata_at)
        VALUES (?, ?, ?, ?, ?)
      `;
			const [result] = await conn.execute(sql, [title, create_id, updata_id, now, now]);
			await conn.commit();
			return { id: result.insertId };
		} catch (error) {
			await conn.rollback();
			throw error;
		} finally {
			conn.release();
		}
	}

	async deletePrints(ids) {
		const conn = await connection.getConnection();
		try {
			await conn.beginTransaction();
			const sql = `
        DELETE FROM sys_print
        WHERE id IN (${ids.map(() => '?').join(',')})
      `;
			const [result] = await conn.execute(sql, ids);
			if (result.affectedRows === 0) {
				throw new Error('没有可删除的模板');
			}
			await conn.commit();
			return { success: true };
		} catch (error) {
			await conn.rollback();
			throw error;
		} finally {
			conn.release();
		}
	}

	async updatePrint({ id, title, updata_id }) {
		const conn = await connection.getConnection();
		try {
			await conn.beginTransaction();
			const sql = `
        UPDATE sys_print
        SET title = ?, updata_id = ?, updata_at = ?
        WHERE id = ?
      `;
			const now = new Date();
			const [result] = await conn.execute(sql, [title, updata_id, now, id]);
			if (result.affectedRows === 0) {
				throw new Error('模板不存在');
			}
			await conn.commit();
			return { success: true };
		} catch (error) {
			await conn.rollback();
			throw error;
		} finally {
			conn.release();
		}
	}

	async getPrintList({ page, limit, title }) {
		const offset = (page - 1) * limit;
		let whereClause = '';
		const params = [];

		if (title) {
			whereClause += ' AND p.title LIKE ?';
			params.push(`%${title}%`);
		}

		const countSql = `
      SELECT COUNT(*) as count
      FROM sys_print p
      WHERE 1=1 ${whereClause}
    `;
		const listSql = `
      SELECT 
        p.id, p.title, p.create_id, p.updata_id,
        p.create_at, p.updata_at,
        c.username AS create_username,
        u.username AS updata_username
      FROM sys_print p
      LEFT JOIN sys_user c ON p.create_id = c.id AND c.del_flag = 'F'
      LEFT JOIN sys_user u ON p.updata_id = u.id AND u.del_flag = 'F'
      WHERE 1=1 ${whereClause}
      ORDER BY p.create_at DESC
      LIMIT ? OFFSET ?
    `;

		const conn = await connection.getConnection();
		try {
			const [countResult] = await conn.execute(countSql, params);
			const [rows] = await conn.execute(listSql, [...params, String(limit), String(offset)]);
			return {
				current: page,
				limit,
				totalPage: Math.ceil(countResult[0].count / limit) || 1,
				total: countResult[0].count,
				rows,
			};
		} catch (error) {
			throw error;
		} finally {
			conn.release();
		}
	}

	async getPrintTemplate(id) {
		const sql = `
      SELECT id, template
      FROM sys_print
      WHERE id = ?
    `;
		const conn = await connection.getConnection();
		try {
			const [rows] = await conn.execute(sql, [id]);
			if (rows.length === 0) {
				throw new Error('模板不存在');
			}
			return rows[0];
		} catch (error) {
			throw error;
		} finally {
			conn.release();
		}
	}

	async savePrintTemplate({ id, template, updata_id }) {
		const conn = await connection.getConnection();
		try {
			await conn.beginTransaction();
			const sql = `
        UPDATE sys_print
        SET template = ?, updata_id = ?, updata_at = ?
        WHERE id = ?
      `;
			const now = new Date();
			const [result] = await conn.execute(sql, [template, updata_id, now, id]);
			if (result.affectedRows === 0) {
				throw new Error('模板不存在');
			}
			await conn.commit();
			return { success: true };
		} catch (error) {
			await conn.rollback();
			throw error;
		} finally {
			conn.release();
		}
	}
}

module.exports = new PrintService();
